require('dotenv').config();

const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const compression = require('compression');
const morgan = require('morgan');

const config = require('./config');
const errorHandler = require('./middleware/error-handler');
const notFoundHandler = require('./middleware/not-found-handler');
const versionManager = require('./middleware/version-manager');
const routes = require('./routes');

class App {
  constructor() {
    this.app = express();
    this.initializeMiddlewares();
    this.initializeRoutes();
    this.initializeErrorHandling();
  }

  initializeMiddlewares() {
    // Security middleware
    this.app.use(helmet());
    this.app.use(cors());
    
    // Compression middleware
    this.app.use(compression());
    
    // Logging middleware
    if (config.app.env !== 'test') {
      this.app.use(morgan('combined'));
    }
    
    // Body parsing middleware
    this.app.use(express.json({ limit: '10mb' }));
    this.app.use(express.urlencoded({ extended: true, limit: '10mb' }));
    
    // API version detection middleware (应用到所有API路由)
    this.app.use('/api', versionManager.detectVersion());
  }

  initializeRoutes() {
    // Welcome page
    this.app.get('/', (req, res) => {
      res.status(200).json({
        message: 'Express + Knex API Server - 清理完成! 🚀🔥',
        version: config.app.version,
        environment: config.app.env,
        lastUpdated: new Date().toISOString(),
        endpoints: {
          health: '/health',
          api_v1: '/api/v1',
          api_v2: '/api/v2',
          api_latest: '/api',
          users_v1: '/api/v1/users',
          users_v2: '/api/v2/users'
        },
        documentation: 'See README.md for API documentation'
      });
    });

    // Health check endpoint
    this.app.get('/health', (req, res) => {
      res.status(200).json({
        status: 'OK',
        timestamp: new Date().toISOString(),
        uptime: process.uptime(),
        environment: config.app.env,
        version: config.app.version,
      });
    });

    // API routes with version support
    this.app.use('/api', routes);
    
    // Version information endpoint
    this.app.get('/api/version', versionManager.getVersionInfo());
  }

  initializeErrorHandling() {
    // 404 handler
    this.app.use(notFoundHandler);
    
    // Global error handler
    this.app.use(errorHandler);
  }

  listen() {
    this.app.listen(config.app.port, () => {
      console.log(`🚀 Server running on port ${config.app.port} in ${config.app.env} mode`);
    });
  }

  getApp() {
    return this.app;
  }
}

module.exports = App;